/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.HashMap;
import java.util.Map;

import com.hiddenequity.adgroup_service.AdGroupResponseParser;
import com.hiddenequity.adgroup_service.AdGroupService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Converter;
import com.hiddenequity.utils.DataValidator;
import com.hiddenequity.utils.Communication;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.EditText;

public class Act_AdGroupOperation extends Act_Super {

	private String campaignId;
	
	private String adGroupId;

	private String campaignBidingStrategy;
	
	private String campaignName;
	
	private String campaignBudget;
	
	private EditText edit_adGroupDefaultBid;

	private EditText edit_adGroupNetworkBid;

	private EditText edit_adGroupName;
	
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.super_operation_layout);
		
		((ViewStub) findViewById(R.id.stub_adgroup_operation)).inflate();
 
        Intent intent = getIntent();
        campaignId = intent.getStringExtra("campaignId");
        campaignBidingStrategy = intent.getStringExtra("campaignBidingStrategy");
        adGroupId = intent.getStringExtra("adGroupId");
        campaignName = intent.getStringExtra("campaignName");
        campaignBudget = intent.getStringExtra("campaignBudget");
        
        title.setText(getString(R.string.title_adgroup_add));
        sub_title.setText(campaignName);
        filter.setVisibility(View.GONE);
        
    	edit_adGroupDefaultBid = (EditText) findViewById(R.id.edit_adGroupDefaultBid);
    	edit_adGroupNetworkBid = (EditText) findViewById(R.id.edit_adGroupNetworkBid);
    	edit_adGroupName = (EditText) findViewById(R.id.edit_adGroupName);
    	
        if(!campaignBidingStrategy.equals("ManualCPC")){
        	edit_adGroupDefaultBid.setEnabled(false);
        	edit_adGroupNetworkBid.setEnabled(false);
        	edit_adGroupNetworkBid.setText(R.string.adgroup_bid_auto);
        }

        if(adGroupId != null){
        	title.setText(getString(R.string.title_adgroup_set));
        	runOperationAsync(OPERATION_GET_DATA, getString(R.string.progress_loading), false);
        }

    }//onCreate

    
    
    /*
     * Get adGroup by id
     */
    Map<String, String> adGroupData = new HashMap<String, String>();
    
    private void getAdGroupData(){
    	adGroupData.clear();
    	AdGroupResponseParser adGroupParser = new AdGroupResponseParser(
    				Communication.postSOAP(
    	    			AdGroupService.URL_ADGROUP_SERVICE, 
    	    			AdGroupService.getAdGroupById(adGroupId)
    	    		)  
    			);
    	
    	responseErrorString = adGroupParser.checkForErrors();
    	adGroupData.putAll(adGroupParser.getAdGroupData());
    }//getAdGroupData
    
    
    
    /*
     * Setup form
     */
    private void setUpForm(){
    	//AdGroup Name
    	edit_adGroupName.setText((CharSequence) adGroupData.get("name"));
    	
    	if(campaignBidingStrategy.equals("ManualCPC")){
        	//AdGroup keywordMaxCpc
        	edit_adGroupDefaultBid.setText(Converter.microamountToStr(adGroupData.get("keywordMaxCpc")));    	
        	//AdGroup keywordMaxCpc
        	if(adGroupData.containsKey("keywordContentMaxCpc")){
            	edit_adGroupNetworkBid.setText(Converter.microamountToStr(adGroupData.get("keywordContentMaxCpc")));           		
        	}
    	} else {
    		edit_adGroupDefaultBid.setText(Converter.microamountToStr(adGroupData.get("keywordMaxCpc")));
    	}
    }//setUpForm
    
    
    
    /*
     * Add campaign (button onClick handler)
     */
    public void onClick_saveData(View v){
    	if(isDataValid()){
    		runOperationAsync(OPERATION_SET_DATA, getString(R.string.progress_saving), false);
    	} else {
    		showOperationError(R.string.msg_title_invalid_data, formErrorString);
    	}
    }//onClick_addAdGroup
    
    
    
    /*
     * Add or set adGroup depends on 
     */
    private void adGroupAddSetOperation(){
		String resp = Communication.postSOAP(
				AdGroupService.URL_ADGROUP_SERVICE, 
				AdGroupService.adGroupOperation(name, campaignId, adGroupId, campaignBidingStrategy, defaultBids, networkBids)
    		);

    	AdGroupResponseParser campaignParser = new AdGroupResponseParser(resp);
    	
    	responseErrorString = campaignParser.checkForErrors();
    }//adGroupAddSetOperation
    
    
    
    /*
     * Collecting and validating form data
     */
    private String name;
    private String defaultBids;
    private String networkBids;

    private boolean isDataValid(){
    	boolean result = true;

    	name = edit_adGroupName.getText().toString();
    	
    	if(!DataValidator.isName(name)) {
    		formErrorString = getString(R.string.msg_invalid_adgroup_name);
    		edit_adGroupName.requestFocus();
    		result = false;
    	} else if(campaignBidingStrategy.equals("ManualCPC")){
        	
        	defaultBids = edit_adGroupDefaultBid.getText().toString();
        	networkBids = edit_adGroupNetworkBid.getText().toString();
        	
        	if(!DataValidator.isAmount(defaultBids, false)) {
        		formErrorString = getString(R.string.msg_invalid_adgroup_defaultbid);
        		edit_adGroupDefaultBid.requestFocus();
        		result = false;
        	} else if(!DataValidator.isAmount(networkBids, true)) {
        		formErrorString = getString(R.string.msg_invalid_adgroup_networkbid);
        		edit_adGroupNetworkBid.requestFocus();
        		result = false;
        	} else if(!DataValidator.isBidNotExceedBudget(defaultBids, campaignBudget)){
        		formErrorString = getString(R.string.msg_api_bid_too_high);
        		edit_adGroupDefaultBid.requestFocus();
        		result = false;
        	} else if(!DataValidator.isBidNotExceedBudget(networkBids, campaignBudget)){
        		formErrorString = getString(R.string.msg_api_bid_too_high);
        		edit_adGroupNetworkBid.requestFocus();
        		result = false;
        	}
        		
    	}
    	return result;
    }//isDataValid  
    
    
    
	/*
	 * Async operation
	 */
	private void runOperationAsync(final int operation, String message, boolean overlap) {

		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_AdGroupOperation.this, getApplication());

				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_GET_DATA:
							Act_AdGroupOperation.this.getAdGroupData();
							break;

						case OPERATION_SET_DATA:
							Act_AdGroupOperation.this.adGroupAddSetOperation();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// Perform postoperation
				Act_AdGroupOperation.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {
							case OPERATION_GET_DATA:
								setUpForm();
								break;

							case OPERATION_SET_DATA:
								if (responseErrorString == null)
									finishActivityWithResult(RESPONSE_REFRESH_REQUIRED);
								break;
							}

						} else {
							Intent intent = new Intent(
									Act_AdGroupOperation.this
											.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();

	}//runOperationAsync
}
